﻿using System;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using log4net;


namespace DevMaker.CM.Mailing.App_code {
    public class GeneraPdfBoleta {
        private static readonly ILog Log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public static void Generar(Boleta boleta) {
            var r = new Rectangle(0, 0, 220, 500);
            var doc = new Document(r);

            try {

                doc.SetMargins(10, 0f, 0f, 0f);

                var filePath = Util.PathFile + "\\" + boleta.TransC_lgnNumber + ".pdf";
                var pw = PdfWriter.GetInstance(doc, new FileStream(filePath, FileMode.Create));
                var font = new Font(Font.FontFamily.HELVETICA, 6);

                doc.Open();
                doc.AddAuthor("Cinemark Chile S.A.");
                doc.AddCreator("Cinemark Chile S.A.");
                doc.AddLanguage("Español");
                doc.AddTitle("Boleta Electronica");

                doc.Add(new Paragraph("CINEMARK CHILE S.A.") { Alignment = Element.ALIGN_CENTER });
                var header =
                    string.Format(
                        "EXPLOTACION DE CINES Y CONFITERIA,{0}CONFITERIA PLATOS PREPARADOS Y PIZZAS{0}{1}{0}" +
                        "R.U.T.:96.659.800-K{0}SUCURSAL:{2}", Environment.NewLine, boleta.Cine.Cinema_strName, boleta.Cine.Cinema_strAddress1);
                doc.Add(new Paragraph(header, font) { Alignment = Element.ALIGN_CENTER });

                var separador = "--------------------------------------------------------------------------------------------------------";
                var separadorTable = "----------------------------------------------------------------------------------------------------  ";
                doc.Add(new Paragraph(separador, font) { Alignment = Element.ALIGN_CENTER });

                var text1 = string.Format("BOLETA ELECTRONICA Nro: {1}{0}" +
                                           "FECHA: {2}{0}" +
                                           "CAJA: {3}", Environment.NewLine, boleta.TransC_strReceiptNumber, boleta.TransC_dtmBKDateCollected
                                           , boleta.TransC_strBKPickupWorkstn);

                doc.Add(new Paragraph(text1, font));
                doc.Add(new Paragraph(separador, font) { Alignment = Element.ALIGN_CENTER });

                PdfPTable table = new PdfPTable(3);
                //PdfPCell cell = new PdfPCell(new Phrase("Header spanning 3 columns"));
                //cell.Colspan = 3;
                //cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
                //table.AddCell(cell);
                float[] widths = new float[] { 70f, 230f, 100f };
                table.SetWidths(widths);

                table.TotalWidth = 205;
                table.DefaultCell.Border = Rectangle.NO_BORDER;
                table.DefaultCell.BorderWidth = 0;
                table.LockedWidth = true;
                table.AddCell(new Paragraph("CANTIDAD", font));
                table.AddCell(new Paragraph("DESCRIPCION", font));
                table.AddCell(new Paragraph("PRECIO", font) { Alignment = Element.ALIGN_RIGHT });
                PdfPCell cell = new PdfPCell(new Paragraph(separadorTable, font) { Alignment = Element.ALIGN_LEFT });
                cell.Border = Rectangle.NO_BORDER;
                cell.Colspan = 3;
                table.AddCell(cell);
                foreach (var detalle in boleta.BoletaDetalles) {
                    cell = new PdfPCell(new Paragraph(detalle.Cantidad.ToString("0000"), font));
                    cell.Border = Rectangle.NO_BORDER;
                    cell.HorizontalAlignment = 2;
                    table.AddCell(cell);
                    table.AddCell(new Paragraph(detalle.NombreItem, font));
                    cell = new PdfPCell(new Paragraph(detalle.ValorLinea.ToString() + "         ", font));
                    cell.Border = Rectangle.NO_BORDER;
                    cell.HorizontalAlignment = 2;
                    table.AddCell(cell);
                }
                cell = new PdfPCell(new Paragraph(separadorTable, font) { Alignment = Element.ALIGN_LEFT });
                cell.Border = Rectangle.NO_BORDER;
                cell.Colspan = 3;
                table.AddCell(cell);


                cell = new PdfPCell(new Paragraph("MONTO TOTAL", font));
                cell.Border = Rectangle.NO_BORDER;
                cell.HorizontalAlignment = 2;
                cell.Colspan = 2;
                table.AddCell(cell);

                cell = new PdfPCell(new Paragraph(boleta.TransC_curValue.ToString("0.##") + "         ", font));
                cell.Border = Rectangle.NO_BORDER;
                cell.HorizontalAlignment = 2;
                table.AddCell(cell);

                doc.Add(table);

                var gif = GenerateFirma(boleta);

                doc.Add(gif);
                var footer = @"
TIMBRE ELECTRONICO S.I.I. RES. 88 DEL 2013
ATENDIDO POR:
Opr :[operador] 
VISTA T/N: [TransC_lgnNumber]

CONSULTE SU BOLETA EN:
****************************WWW.CINEMARK.CL**************************** 
";
                var foo = (new Paragraph(
                    footer.Replace("[operador]", boleta.Operador).
                    Replace("[TransC_lgnNumber]", boleta.TransC_lgnNumber.ToString()),
                            font) { Alignment = Element.ALIGN_CENTER });
                doc.Add(foo);
                doc.CloseDocument();

                BoletaDao.InsertTracking(boleta, "Gen_Pdf", null);
            } catch (Exception ex) {
                Log.Error(ex);
                BoletaDao.InsertTracking(boleta, "Gen_Pdf", ex);
            }

        }

        public static Image GenerateFirma(Boleta boleta) {
            try {
                var pdf417 = new BarcodePDF417 {
                    CodeRows = 5,
                    CodeColumns = 18,
                    ErrorLevel = 5,
                    LenCodewords = 999,
                    Options = BarcodePDF417.PDF417_FORCE_BINARY
                };

                pdf417.SetText(boleta.TickNum_strStyleCode);
                var image = pdf417.GetImage();
                image.ScaleAbsolute(184, 72);
                image.Alignment = 2;
                image.Alignment = Element.ALIGN_CENTER;
                return image;
            } catch (Exception ex) {
                Log.Error(ex);
                throw;
            }
        }
    }
}
